package com.example.course

import androidx.appcompat.app.AppCompatActivity
import android.app.Activity
import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.Toast

class AddCourseActivity : AppCompatActivity() {

    lateinit var inputCourseName: EditText
    lateinit var inputTeacher: EditText
    lateinit var inputClassRoom: EditText
    lateinit var inputDay: Spinner
    lateinit var inputStart: Spinner
    lateinit var inputEnd: Spinner
    var isRevise = false
    private val databaseHelper = DatabaseHelper(this, "database.db", null, 1)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_course)
        setFinishOnTouchOutside(false)

        inputCourseName = findViewById(R.id.course_name)
        inputTeacher = findViewById(R.id.teacher_name)
        inputClassRoom = findViewById(R.id.class_room)
        inputDay = findViewById(R.id.week)
        inputStart = findViewById(R.id.classes_begin)
        inputEnd = findViewById(R.id.classes_ends)

        val intent = intent
        val reviseCourse = intent.getSerializableExtra("ReviseCourse") as Course?
        isRevise = intent.getBooleanExtra("isRevise", false)

        val okButton: Button = findViewById(R.id.button)

        if (isRevise && reviseCourse != null) {
            inputCourseName.setText(reviseCourse.courseName)
            inputClassRoom.setText(reviseCourse.classRoom)
            inputTeacher.setText(reviseCourse.teacher)
            setSpinnerDefaultValue(inputDay, reviseCourse.day.toString())
            setSpinnerDefaultValue(inputStart, reviseCourse.classStart.toString())
            setSpinnerDefaultValue(inputEnd, reviseCourse.classEnd.toString())

            okButton.setOnClickListener {
                val courseName = inputCourseName.text.toString()
                val teacher = inputTeacher.text.toString()
                val classRoom = inputClassRoom.text.toString()
                val day = inputDay.selectedItem.toString()
                val start = inputStart.selectedItem.toString()
                val end = inputEnd.selectedItem.toString()

                if (courseName.isEmpty() || day.isEmpty() || start.isEmpty() || end.isEmpty()) {
                    Toast.makeText(this, "基本课程信息未填写", Toast.LENGTH_SHORT).show()
                } else {
                    val newCourse = Course(courseName, teacher, classRoom,
                        day.toInt(), start.toInt(), end.toInt())

                    if (isCourseConflict(newCourse, reviseCourse)) {
                        Toast.makeText(this, "该时间段已有课程，发生冲突", Toast.LENGTH_SHORT).show()
                    } else {
                        val intent = Intent()
                        intent.putExtra("PreCourse", reviseCourse)
                        intent.putExtra("newCourse", newCourse)
                        setResult(Activity.RESULT_OK, intent)
                        finish()
                    }
                }
            }
        } else {
            okButton.setOnClickListener {
                val courseName = inputCourseName.text.toString()
                val teacher = inputTeacher.text.toString()
                val classRoom = inputClassRoom.text.toString()
                val day = inputDay.selectedItem.toString()
                val start = inputStart.selectedItem.toString()
                val end = inputEnd.selectedItem.toString()

                if (courseName.isEmpty() || day.isEmpty() || start.isEmpty() || end.isEmpty()) {
                    Toast.makeText(this, "基本课程信息未填写", Toast.LENGTH_SHORT).show()
                } else {
                    val course = Course(courseName, teacher, classRoom,
                        day.toInt(), start.toInt(), end.toInt())

                    if (isCourseConflict(course)) {
                        Toast.makeText(this, "该时间段已有课程，发生冲突", Toast.LENGTH_SHORT).show()
                    } else {
                        val intent = Intent()
                        intent.putExtra("course", course)
                        setResult(Activity.RESULT_OK, intent)
                        finish()
                    }
                }
            }
        }
    }

    private fun isCourseConflict(course: Course, excludeCourse: Course? = null): Boolean {
        val sqLiteDatabase = databaseHelper.writableDatabase
        val query = if (excludeCourse != null) {
            "SELECT * FROM courses WHERE day = ? AND class_start < ? AND class_end > ? AND NOT (course_name = ? AND day = ? AND class_start = ? AND class_end = ?)"
        } else {
            "SELECT * FROM courses WHERE day = ? AND class_start < ? AND class_end > ?"
        }
        val args = if (excludeCourse != null) {
            arrayOf(course.day.toString(), course.classEnd.toString(), course.classStart.toString(),
                excludeCourse.courseName, excludeCourse.day.toString(), excludeCourse.classStart.toString(), excludeCourse.classEnd.toString())
        } else {
            arrayOf(course.day.toString(), course.classEnd.toString(), course.classStart.toString())
        }
        val cursor = sqLiteDatabase.rawQuery(query, args)
        val conflict = cursor.moveToFirst()
        cursor.close()
        return conflict
    }

    private fun setSpinnerDefaultValue(spinner: Spinner, value: String) {
        val adapter = spinner.adapter
        val size = adapter.count
        for (i in 0 until size) {
            if (TextUtils.equals(value, adapter.getItem(i).toString())) {
                spinner.setSelection(i, true)
                break
            }
        }
    }
}